<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta content="webkit" name="renderer">
    <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport">
    <link href="../static/layui/css/layui.css" media="all" rel="stylesheet">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

</head>
<body>

<form action="" class="layui-form" enctype="multipart/form-data" id="addForm" lay-filter="add"
      style="display:none">

    <div class="layui-form-item">
        <label class="layui-form-label">仓库编号</label>
        <div class="layui-input-block">
            <input autocomplete="off" class="layui-input" id="houseCode" lay-verify="required"
                   name="houseCode"
                   placeholder="仓库编号" type="text">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">仓库名称</label>
        <div class="layui-input-block">
            <input autocomplete="off" class="layui-input" id="houseName" lay-verify="required"
                   name="houseName"
                   placeholder="仓库名称" type="text">
        </div>
    </div>


    <div class="layui-form-item" id="sub">
        &nbsp;&nbsp;&nbsp;<button class="layui-btn" id="addsub" lay-filter="demo2" lay-submit
                                  style="" type="button">提交
    </button>
    </div>
</form>


<table class="layui-hide" id="test" lay-filter="test"></table>
<!--修改的from表单 -->
<form action="" class="layui-form" enctype="multipart/form-data" id="updataForm" lay-filter="updata"
      style="display:none">
    <div class="layui-form-item" style="display:none">
        <label class="layui-form-label">id</label>
        <div class="layui-input-block">
            <input autocomplete="off" class="layui-input" id="id" lay-verify="id" name="id" placeholder="id"
                   type="text">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">仓库编号</label>
        <div class="layui-input-block">
            <input autocomplete="off" class="layui-input layui-disabled" id="houseCode" lay-verify="required"
                   name="houseCode"
                   placeholder="仓库编号" type="text">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">仓库名称</label>
        <div class="layui-input-block">
            <input autocomplete="off" class="layui-input" id="houseName" lay-verify="required"
                   name="houseName"
                   placeholder="仓库名称" type="text">
        </div>
    </div>


    <div class="layui-form-item" id="sub">
        &nbsp;&nbsp;&nbsp;<button class="layui-btn" id="updatasub" lay-filter="demo3" lay-submit
                                  style="" type="button">确认
    </button>
    </div>
</form>

<script id="toolbarDemo" type="text/html">
    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-sm" id="add" lay-event="add">添加</button>
    </div>
</script>


<script id="barDemo" type="text/html">
    <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script charset="utf-8" src="../static/layui/layui.js"></script>


<script>


    layui.use('table', function () {
        var table = layui.table;

        table.render({
            elem: '#test'
            , url: 'http://localhost:8082/house/list'
            , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            , defaultToolbar: ['filter', 'exports', 'print']
            , title: '用户数据表'
            , cols: [
                [
                    {type: 'checkbox', fixed: 'left', sort: true}
                    , {field: 'id', title: 'id', width: 200}
                    , {field: 'houseCode', title: '仓库编号', width: 200}
                    , {field: 'houseName', title: '仓库名称', width: 200}
                    , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 150}
                ]
            ]
            , page: false
            , response: {
                statusName: 'status' //规定数据状态的字段名称，默认：code
                , dataName: 'rows' //规定数据列表的字段名称，默认：data
            }
            , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                return {
                    "status": res[0].status,   //解析接口状态
                    "message": res[1].message,  //解析提示文本
                    "count": 10,       //解析数据长度
                    "rows": res[3].rows.item  //解析数据列表
                };
            }
        });


        //头工具栏事件
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'add':
                    add();
                    break;
            }
            ;
        });

        //监听行工具事件
        table.on('tool(test)', function (obj) {
            var data = obj.data;

            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    obj.del();
                    deleteById(data.id);
                    layer.close(index);
                });
            } else if (obj.event === 'edit') {
                form.val("updata", {
                    "id": data.id // "name": "value"
                    , "name": data.name
                    , "houseName": data.houseName
                    , "houseCode": data.houseCode
                });
                updateById(data);
            }
        });

        //添加的from表单
        layui.use(['form', 'laydate'], function () {
            form = layui.form;
            form.render();

            //增加的form
            form.on('submit(demo2)', function (data) {
                console.log(JSON.stringify(data.field));
                $.ajax({
                    url: 'http://localhost:8082/house/saveOrUpdate',
                    method: 'get',

                    data: data.field,
                    dataType: 'JSON',
                    success: function (res) {
                        if (res.status == 0) {
                            //console.log(res);
                            layer.msg("添加成功");
                            $("#addForm")[0].reset();
                            form.render();
                            //刷新页面
                            table.reload('test', {
                                url: 'http://localhost:8082/house/list'
                            });
                        } else if (res.status == 1) {

                            layer.msg("仓库编号不允许重复");
                            $("#addForm")[0].reset();
                            form.render();
                        } else {
                            layer.msg("添加失败");
                            $("#addForm")[0].reset();
                            form.render();
                        }
                    },
                    error: function (data) {
                        layer.msg("网络错误");
                        $("#addForm")[0].reset();
                        form.render();
                    }
                });
                layer.close(layer_index);
            });

            //修改的form表单
            form.on('submit(demo3)', function (data) {
                console.log(JSON.stringify(data.field));
                $.ajax({
                    url: 'http://localhost:8082/house/saveOrUpdate',
                    method: 'get',
                    data: data.field,
                    dataType: 'JSON',
                    success: function (res) {
                        if (res.status == 0) {
                            //console.log(res);
                            layer.msg("修改成功");
                            $("#updataForm")[0].reset();
                            form.render();
                            table.reload('test', {
                                url: 'http://localhost:8082/house/list'
                            });

                        } else {
                            layer.msg("修改成功");
                            $("#updataForm")[0].reset();
                            form.render();
                        }
                    },
                    error: function (data) {
                        layer.msg("网络错误");
                        $("#updataForm")[0].reset();
                        form.render();
                    }
                });
                layer.close(layer_index);
            });

        });

        //修改
        function updateById(data) {

            layer_index = layer.open({
                type: 1,  //可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                title: "修改",
                area: ['500px', '400px'], //所打开页面大小
                content: $("#updataForm"), //内容


                //关闭操作
                cancel: function () {
                    layer.close(layer_index);
                    $("#updataForm")[0].reset();

                }
            });

        }

        function add() {
            layer_index = layer.open({
                type: 1,  //可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                title: "添加",
                area: ['500px', '400px'], //所打开页面大小
                content: $("#addForm"), //内容
                //关闭操作
                cancel: function () {
                    layer.close(layer_index);
                    $("#addForm")[0].reset();
                    $('#demoe1').attr('src', "");
                }
            });

        }


        //删除
        function deleteById(index) {

            var url = "http://localhost:8082/house/deleteById";
            $.ajax({
                type: "get",
                url: url,    //传输地址的URL
                data: {"id": index},
                dataType: 'JSON',
                async: false,
                success: function (res) {
                    if (res.status == 0) {
                        layer.msg("删除成功");
                    } else if (res.status == 1) {
                        layer.msg("该仓库中含有商品，不可删除")
                    }

                    table.reload('test', {
                        url: 'http://localhost:8082/house/list'
                    });

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(typeof (errorThrown));
                }
            });
        }

        layui.use('laydate', function () {
            var laydate = layui.laydate;
            laydate.render({
                elem: '#ftime',
                type: 'datetime'
            });
        });

    });


</script>

</body>
</html>